import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:im_app/im/page/sub/GroupAddPage.dart';
import 'package:im_app/im/page/sub/GroupChangeDescriptionPage.dart';
import 'package:im_app/im/page/sub/GroupChangeNamePage.dart';
import 'package:im_app/im/page/sub/GroupUserListPage.dart';
import 'package:im_app/im/page/sub/SessionSettingBase.dart';
import 'package:im_app/im/page/view/ListSeparator.dart';
import 'package:im_app/im/page/view/MovableView.dart';
import 'package:im_app/im/page/view/component/GroupIconView.dart';
import 'package:im_app/im/page/view/component/UiUtil.dart';
import 'package:provider/provider.dart';

import '../../pojo/ImPojo.dart';
import '../../service/ImMessageService.dart';
import '../../util/ImConstant.dart';
import '../../util/ImSingleton.dart';
import '../bloc/GroupAddCubit.dart';
import '../bloc/GroupUserListCubit.dart';
import '../bloc/MessageHistoryCubit.dart';
import '../bloc/SelectUsersCubit.dart';
import '../bloc/SessionSettingCubit.dart';
import 'GroupChangeUserNamePage.dart';
import 'MessageHistorySearchPage.dart';

typedef RowTrailFunction = Widget Function(BuildContext context);

/// 会话群管理
class SessionGroupSettingPage extends SessionSettingBase {

  const SessionGroupSettingPage({super.key});

  @override
  Widget build(BuildContext context) {
    var sessionSettingCubit = context.watch<SessionSettingCubit>();
    var session = sessionSettingCubit.session;
    return Scaffold(
      appBar: _buildAppBar(context),
      backgroundColor: ImConstant.IM_RESERVE_BACKGROUND_COLOR,
      body: SafeArea(
        child: MovableView(
          headMoveMaxHeight: 100,
          trailMoveMaxHeight: 100,
          backgroundColor: ImConstant.IM_MAIN_BACKGROUND_COLOR,
          widgetBuilder: (context) => NotificationListener(
              onNotification: (ScrollNotification notification) {
                if (notification is OverscrollNotification && notification.overscroll < 0) {
                  // 用户向下滑动，ListView已经滑动到顶部，处理GestureDetector的滑动事件
                  print("scroll end !!!!!!!!!!!!!!!!!!!");
                  return true;
                }
                return true;
              },
              child: CustomScrollView(scrollDirection: Axis.vertical, reverse: false, slivers: [
                _buildGroupUsers(context),
                if ((session.group?.groupUserList?.length ?? 0) > 19) _buildMoreGroupUsers(context),
                SliverList(
                  delegate: SliverChildListDelegate(<Widget>[
                    _buildRowSeparator(8),
                    ListTile(title: const Text('群聊名称'),
                      trailing: Text.rich(TextSpan(
                        children: [
                          TextSpan(text: session.name, style: const TextStyle(color: Colors.grey, fontSize: 11)),
                          const WidgetSpan(child: Icon(Icons.chevron_right, ), alignment: PlaceholderAlignment.middle),
                        ],
                      ),),
                      onTap: () {
                        Navigator.of(context).push(MaterialPageRoute(
                            builder: (context) => GroupChangeNamePage(session: session)));
                      }),

                    ListSeparator(indent: 10,),

                    ListTile(title: const Text('群二维码'),
                        trailing: Text.rich(TextSpan(
                          children: [
                            WidgetSpan(child: buildSvgView('assets/svg/qrcode.svg', 20, 20, Colors.grey),),
                            const WidgetSpan(child: Icon(Icons.chevron_right), alignment: PlaceholderAlignment.middle),
                          ],
                        )),
                        onTap: () {
                          // Navigator.of(context).push(MaterialPageRoute(
                          //     builder: (context) => GroupChangeNamePage(session: widget.session)));
                        }),

                    ListSeparator(indent: 10,),
                    _buildGroupDescriptionPane(context), // 群介绍
                    _buildRowSeparator(8),
                    ListTile(
                      title: const Text('查找聊天记录'),
                      trailing: const Icon(Icons.keyboard_arrow_right),
                      onTap: () {
                        Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                          var messageHistoryCubit = BlocProvider.of<MessageHistoryCubit>(context);
                          messageHistoryCubit.add(MessageHistoryInitEvent(session.id!));
                          return MessageHistorySearchPage(
                            session: session,
                          );
                        }));
                      },
                    ),
                    _buildRowSeparator(8),
                    ListTile(
                      title: const Text('消息免打扰'),
                      trailing: Switch(
                        value: !isDisturb(session),
                        onChanged: (value) {
                          sessionSettingCubit.add(SessionSettingDisturbEvent(!value));
                          // setState(() {
                          //   session.isDisturb = !session.isDisturb;
                          // });
                        },
                      ),
                    ),
                    ListSeparator(indent: 10,),
                    ListTile(
                        title: const Text('置顶聊天'),
                        trailing: Switch(
                          value: isTop(session),
                          onChanged: (value) {
                            sessionSettingCubit.add(SessionSettingTopEvent(value));
                          },
                        )),
                    _buildRowSeparator(8),

                    ListTile(title: const Text('我在群里的昵称'),
                        trailing: Text.rich(TextSpan(
                          children: [
                            TextSpan(text: session.group?.currentGroupUser?.userName??
                                (session.group?.currentGroupUser?.user?.userName??''),
                                style: const TextStyle(color: Colors.grey, fontSize: 11)),
                            const WidgetSpan(child: Icon(Icons.chevron_right, ), alignment: PlaceholderAlignment.middle),
                          ],
                        ),),
                        onTap: () {
                          Navigator.of(context).push(MaterialPageRoute(
                              builder: (context) => GroupChangeUserNamePage(session: session)));
                        }),

                    ListTile(
                      title: const Text('显示群成员昵称'),
                      trailing: Switch(
                        value: session.group?.currentGroupUser?.isShowName??false,
                        onChanged: (value) {
                          sessionSettingCubit.add(SessionSettingShowNameEvent(value));
                        },
                      ),
                    ),
                    _buildRowSeparator(8),
                    ListTile(
                      title: const Text('设置当前聊天背景'),
                      trailing: const Icon(Icons.keyboard_arrow_right),
                      onTap: () {},
                    ),
                    _buildRowSeparator(8),
                    ListTile(
                      title: const Text('清空聊天记录'),
                      trailing: const Icon(Icons.keyboard_arrow_right),
                      onTap: ()=> cleanMessages(context, session),
                    ),
                    ListSeparator(
                      indent: 10,
                    ),
                    ListTile(
                      title: const Text('投诉'),
                      trailing: const Icon(Icons.keyboard_arrow_right),
                      onTap: () {},
                    ),
                    _buildRowSeparator(8),
                  ]),
                ),
              ])),
        ),
      ),
    );
  }

  AppBar _buildAppBar(BuildContext context) {
    var session = context.watch<SessionSettingCubit>().session;
    return AppBar(
      leading: InkWell(
        child: const Icon(Icons.chevron_left),
        onTap: () {
          Navigator.of(context).pop();
        },
      ),
      title: Text(
        "聊天信息(${session.group?.groupUserList?.length ?? 0})",
        style: const TextStyle(fontSize: ImConstant.IM_DEFAULT_SIZE, fontWeight: FontWeight.w500),
      ),
      toolbarHeight: ImConstant.IM_APP_BAR_HEIGTH,
      backgroundColor: ImConstant.IM_MAIN_BACKGROUND_COLOR,
      centerTitle: true,
    );
  }

  Widget _buildGroupUsers(BuildContext context) {
    return SliverGrid(
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 5, childAspectRatio: 1, crossAxisSpacing: 0.0, mainAxisSpacing: 0.0),
      delegate: SliverChildListDelegate(_buildGroupUserItems(context)),
    );
  }

  Widget _buildMoreGroupUsers(BuildContext context) {
    return SliverToBoxAdapter(
      child: Container(
          padding: const EdgeInsets.only(top: 5),
          color: ImConstant.IM_RESERVE_BACKGROUND_COLOR,
          child: Material(
            color: ImConstant.IM_RESERVE_BACKGROUND_COLOR,
            child: InkWell(
              child: const Padding(
                padding: EdgeInsets.only(top: 10, bottom: 10),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [Text('查看更多群成员'), Icon(Icons.keyboard_arrow_right)],
                ),
              ),
              onTap: () {
                var sessionSettingCubit = context.read<SessionSettingCubit>();
                var session = sessionSettingCubit.session;
                Navigator.of(context).push(MaterialPageRoute(builder: (context){
                  return BlocProvider(create: (context)=> GroupUserListCubit(session),
                    child: const GroupUserListPage(),);
                }));
              },
            ),
          )),
    );
  }

  List<Widget> _buildGroupUserItems(BuildContext context) {
    var session = context.watch<SessionSettingCubit>().session;
    var array = <Widget>[];
    int size = 0;
    if (session.group != null) {
      for (var gu in session.group!.groupUserList!) {
        size++;
        var widget = _buildGroupUserItem(session.group!, gu);
        array.add(widget);
        if (size >= 19) break;
      }
    }
    array.add(_buildAddUserGroup(context, session));
    return array;
  }

  Widget _buildGroupUserItem(ImGroup group, ImGroupUser guUser) {
    return Container(
      // width: 80,
      // height: 80,
      color: ImConstant.IM_RESERVE_BACKGROUND_COLOR,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          ClipRRect(
              borderRadius: BorderRadius.circular(5),
              child: GroupIconView(group: group, iconSize: ImConstant.IM_USER_ICON_SIZE,),
          ),
          Text(guUser.userName ?? (guUser.user?.userName??guUser.userId))
        ],
      ),
    );
  }

  Widget _buildAddUserGroup(BuildContext context, ImSession session) {
    return InkWell(
      child: const Icon(Icons.add),
      onTap: () async {
        Navigator.of(context).push(MaterialPageRoute(builder: (context){
          return buildGroupCubit(session, const GroupAddPage());
        }));
      },
    );
  }

  Widget _buildGroupDescriptionPane(BuildContext context) {
    var session = context.watch<SessionSettingCubit>().session;
    return InkWell(child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        const Padding(
          padding: EdgeInsets.only(top: 15, left: 10),
          child: Text('群公告'),
        ),
        Padding(
          padding: const EdgeInsets.only(top: 5, left: 10, right: 10, bottom: 10),
          child: Text(
            session.group?.description??'',
            style: const TextStyle(fontSize: ImConstant.IM_SMALL_SIZE),
          ),
        )
      ],
    ), onTap: () {
      Navigator.of(context).push(MaterialPageRoute(builder: (context) {
        return GroupChangeDescriptionPage(session: session);
      }));
    },);
  }

  Widget _buildRowSeparator(double height) {
    return Container(
      color: ImConstant.IM_MAIN_BACKGROUND_COLOR,
      height: height,
    );
  }
}
